<?php
session_set_save_handler('_open',
             '_close',
             '_read',
             '_write',
             '_destroy',
             '_clean');
session_start();

function _open(){
	global $db;
	return ;
}

function _close(){
  global $db;
  return ;
}

function _read($id){
	global $db;
	$id = mysql_real_escape_string($id);

	$sql = 'SELECT session_data
      FROM '.PREFIX.'sec_session
      WHERE session_id="'.$id.'" AND expire>'.time();
	$session_data = $db->GetOne($sql, 'fw');
	if ($session_data) {
		return $session_data;
	}
  return ;
}

function _write($id, $data){
	global $driver,$username,$password,$hostname,$databasename;

	if ($_SESSION[SESSION_L]>0) {
		$db =& ADONewConnection($driver.'://'.$username.':'.$password.'@'.$hostname.'/'.$databasename);
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
		$db->Execute('SET NAMES UTF8', 'fw');

	  $id = mysql_real_escape_string($id);
	  $data = mysql_real_escape_string($data);

	  $url = basename($_SERVER['REQUEST_URI']);
	  $sql = 'SELECT id, session_lifetime FROM '.PREFIX.'sec_session WHERE session_id="'.$id.'" AND expire>'.time();
	  $rsl = $db->GetRow($sql, 'fw');
	  if ($rsl) {
	  	if($_REQUEST['ajax'] == 1) {
		  	$url = '';
	  	} else {
	  		$url = ', url="'.$url.'"';
	  	}
	    $sql = 'UPDATE '.PREFIX.'sec_session SET created='.time().', expire='.strtotime('+'.$rsl['session_lifetime'].' seconds').', session_data="'.$data.'"'.$url.' WHERE id="'.$rsl['id'].'"';
	    return $db->Execute($sql, 'fw');
	  } else {
		$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
		$country_name = substr($hostname,strrpos($hostname,".")+1);
		if (!strstr($hostname,'.') || !ereg('[A-Za-z]+', $country_name)) {
			$country_name = '';
		}
		$sql = 'INSERT INTO '.PREFIX.'sec_session(id_user, username, created, expire, session_lifetime, ip, hostname, country_name, url, session_id, session_data)
		VALUES('.$_SESSION[SESSION_L].', "'.$_SESSION[SESSION_A]['login'].'", '.time().', '.strtotime('+'.SESSION_LIFETIME.' seconds').', '.SESSION_LIFETIME.', "'.$_SERVER['REMOTE_ADDR'].'", "'.$hostname.'", "'.$country_name.'", "'.$url.'", "'.$id.'", "'.$data.'")';
		return $db->Execute($sql, 'fw');
	  }
	}
	return ;
}

function _destroy($id){
	global $db;
	$sql = 'UPDATE '.PREFIX.'sec_session SET expire='.time().' WHERE session_id="'.$id.'" AND expire>'.time();
	return $db->Execute($sql, 'fw');
}

function _clean($max){
	global $db;
	return;
}

function session_add_url_title($title){
	global $db;
	if ($title != '') $title = $title.' | ';
	$title .= GAIN_PROJECT_NAME;

	$sql = 'SELECT id FROM '.PREFIX.'sec_session WHERE session_id="'.session_id().'" AND expire>'.time();
	$id = $db->GetOne($sql, 'fw');
	if ($id) {
		$sql = SQL('UPDATE '.PREFIX.'sec_session SET url_name=%s WHERE id=%d', $title, $id);
		$db->Execute($sql, 'fw');
	}
}
